//
//  NewPointOfMessageButton.swift
//  letuofu
//
//  Created by Julien Yan on 2020/10/21.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit

class UnreadPointForNewsButton {
    
    static var unreadFlag : Bool? = nil
    
    static let allInstance = NSMapTable<UIView, UnreadPointForNewsButton>(
        keyOptions: .weakMemory, valueOptions: .strongMemory)
    
    static func checkUpdateUnreadFlag(point:UIView? = nil){
        if (point != nil) && (UnreadPointForNewsButton.unreadFlag != nil) {
            point!.isHidden = !(UnreadPointForNewsButton.unreadFlag!)
            return
        }
        API.formRequest(url: .A_getUnreadSyspushdescList, params:
            ["pageIndex":"1",
                "pageNum":"10",
                "guid":LocalStorage.getString(forKey: USER_GUID)!
            ], callback: { (result) in
            if result.success {
                UnreadPointForNewsButton.unreadFlag = false
                if let dl = result.data?.getDictList("data") {
                    if let _ = dl.first(where: { (data) -> Bool in
                        return data.getInt("readed") == 0
                    }) {
                        UnreadPointForNewsButton.unreadFlag = true
                    }
                }
                if let pointIterator = UnreadPointForNewsButton.allInstance.objectEnumerator() {
                    for value in pointIterator {
                        if let pointContainer = value as? UnreadPointForNewsButton {
                            pointContainer.point?.isHidden = !(UnreadPointForNewsButton.unreadFlag!)
                        }
                    }
                }
            }
        })
    }
    
    weak var point : UIView?
    
    @discardableResult
    init(button : UIButton,pointRadius:CGFloat,pointOffset:CGPoint,color:UIColor){
        self.point = button.drawView() { (make) in
            make.centerX.equalTo(button.snp.right).offset(pointOffset.x)
            make.centerY.equalTo(button.snp.top).offset(pointOffset.y)
            make.width.height.equalTo(pointRadius*2)
        }
        point!.cornerRadius(pointRadius)
        point!.backgroundColor = color
        point!.isHidden = true
        UnreadPointForNewsButton.allInstance.setObject(self, forKey: button)
        UnreadPointForNewsButton.checkUpdateUnreadFlag(point: point)
    }
}
